import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

export interface ChatMessage {
  id: string;
  senderId: string;
  receiverId: string;
  content: string;
  timestamp: number;
  status: 'sending' | 'delivered' | 'read' | 'failed';
}

interface Props {
  message: ChatMessage;
  currentUserId: string;
}

const ChatMessage: React.FC<Props> = ({ message, currentUserId }) => {
  const isSender = message.senderId === currentUserId;

  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'sending': return '发送中...';
      case 'delivered': return '已发送';
      case 'read': return '已读';
      case 'failed': return '发送失败';
      default: return '';
    }
  };

  return (
    <View style={[styles.container, isSender ? styles.senderContainer : styles.receiverContainer]}>
      <View style={[styles.messageBox, isSender ? styles.senderBox : styles.receiverBox]}>
        <Text style={[styles.messageText, isSender ? styles.senderText : styles.receiverText]}>
          {message.content}
        </Text>
        <View style={styles.messageFooter}>
          <Text style={styles.timeText}>{formatTime(message.timestamp)}</Text>
          {isSender && (
            <Text style={[styles.statusText, message.status === 'failed' && styles.failedStatus]}>
              {getStatusText(message.status)}
            </Text>
          )}
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 8,
    flexDirection: 'row',
    marginVertical: 2,
  },
  senderContainer: {
    justifyContent: 'flex-end',
  },
  receiverContainer: {
    justifyContent: 'flex-start',
  },
  messageBox: {
    maxWidth: '70%',
    borderRadius: 12,
    padding: 10,
  },
  senderBox: {
    backgroundColor: '#007AFF',
    borderBottomRightRadius: 4,
  },
  receiverBox: {
    backgroundColor: '#E8E8E8',
    borderBottomLeftRadius: 4,
  },
  messageText: {
    fontSize: 16,
    lineHeight: 20,
  },
  senderText: {
    color: '#FFFFFF',
  },
  receiverText: {
    color: '#000000',
  },
  messageFooter: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
    marginTop: 4,
  },
  timeText: {
    fontSize: 12,
    color: '#8E8E93',
    marginRight: 4,
  },
  statusText: {
    fontSize: 12,
    color: '#8E8E93',
  },
  failedStatus: {
    color: '#FF3B30',
  },
});

export default ChatMessage;